<template>
  <div class='add-container'>
<el-card :header="$route.query.id?'试题修改':'试题录入'">
  <el-form label-width="120px" :model="form" :rules="rules" ref="questionForm">
    <el-form-item label="学科： " prop="subjectID">
      <el-select v-model="form.subjectID" placeholder="请选择" style="width:400px" @change="hChange" >
        <el-option :label="item.subjectName" :value="item.id" v-for="item in subjectList" :key="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="目录： " prop="catalogID">
        <el-select v-model="form.catalogID" placeholder="请选择" style="width:400px">
          <el-option  :label="item.label" :value="item.value" v-for="item in directoryList" :key="item.value"></el-option>
        </el-select>
    </el-form-item>
    <el-form-item label="企业： " prop="enterpriseID">
      <el-select v-model="form.enterpriseID" placeholder="请选择" style="width:400px">
        <el-option :label="item.company" :value="item.id" v-for="item in companyList" :key="item.id" ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="城市： " prop="city">
      <el-row justify="space-between" type="flex" :gutter="5" style="width:405px" >
        <el-col :span="12">
          <el-select v-model="form.province" placeholder="请选择" style="width:100%" @change="changeCity">
            <el-option :label="item" :value="item" v-for="item in cityList" :key="item" ></el-option>
          </el-select>
        </el-col>
        <el-col :span="12">
          <el-select v-model="form.city" placeholder="请选择" style="width:100%">
            <el-option :label="item" :value="item" v-for="item in areaList" :key="item"></el-option>
          </el-select>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="方向： " prop="direction">
      <el-select v-model="form.direction" placeholder="请选择" style="width:400px">
        <el-option :label="item" :value="item" v-for="item in direction" :key="item"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="题型： " prop="questionType">
    <el-radio-group v-model="form.questionType" style="width:400px">
      <el-radio label="1">单选</el-radio>
      <el-radio label="2">多选</el-radio>
      <el-radio label="3">简答</el-radio>
    </el-radio-group>
    </el-form-item>
    <el-form-item label="难度： " prop="difficulty">
      <el-radio-group v-model="form.difficulty" style="width:400px">
        <el-radio label="1">简单</el-radio>
        <el-radio label="2">一般</el-radio>
        <el-radio label="3">困难</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="题干： " prop="question">
     <quill-editor v-model="form.question" :options="editorOption"></quill-editor>
    </el-form-item>
    <el-form-item label="选项： "  v-if="form.questionType==='1'">
        <el-radio-group v-model="isCheck" >
          <el-row style="width:400px" class="select" v-for="item in form.options" :key="item.code">
            <el-radio :label="item.code">{{item.code +'：'}}</el-radio>
            <el-input  style="width:240px" v-model="item.title"></el-input>
            <el-upload
              class="avatar-uploader"
              ref="avatarUploader"
              action="#"
              :show-file-list="false"
              :http-request="upload"
              :data="{code:item.code}"
              :on-remove="removeImg"
              :before-upload="beforeAvatarUpload"
              >
              <img v-if="item.img" :src="item.img" class="avatar">

              <el-button class="upload-button">上传图片</el-button>
            </el-upload>
            <i class="el-icon-circle-close" v-show="item.img!==''" @click="removeImg(item.code)"></i>
          </el-row>
           <el-button type="danger" size="small"  :disabled="form.questionType==='1'">+新增选项与答案</el-button>
        </el-radio-group>
    </el-form-item>
    <el-form-item label="选项： "  v-if="form.questionType==='2'">
        <el-checkbox-group v-model="isCheck" >
          <el-row style="width:400px" class="select" v-for="(item,index) in form.options" :key="item.code">
            <el-checkbox  :label="item.code">{{item.code +'：'}}</el-checkbox>
            <el-input  style="width:240px" v-model="item.title"></el-input>
            <el-upload
              class="avatar-uploader"
              action="#"
              ref="avatarUploader"
              :show-file-list="false"
              :http-request="upload"
              :on-remove="removeImg"
              :data="{code:item.code}"
              :before-upload="beforeAvatarUpload">
              <img v-if="item.img" :src="item.img" class="avatar">
              <el-button class="upload-button">上传图片</el-button>
            </el-upload>
            <i class="el-icon-circle-close" v-show="item.img!==''|| form.options.length===index+1" @click="delChoice(item.code)"></i>
          </el-row>
          <el-button type="danger" size="small" :disabled="form.questionType==='1' || form.options.length===12" @click="addChoice">+新增选项与答案</el-button>
        </el-checkbox-group>

    </el-form-item>
    <el-form-item label="视频解析： " >
     <el-input style="width:400px" v-model="form.videoURL"></el-input>
    </el-form-item>
    <el-form-item label="答案解析： " prop="answer">
     <quill-editor v-model="form.answer" :options="editorOption"></quill-editor>
    </el-form-item>
    <el-form-item label="题目备注： " >
      <el-input  type="textarea" style="width:400px" rows="4" v-model="form.remarks"></el-input>
    </el-form-item>
     <el-form-item label="试题标签： ">
        <el-select v-model="form.tags" placeholder="请选择试题标签" style="width:400px" multiple>
          <el-option  :label="item.label" :value="item.value" v-for="item in tagList" :key="item.value"></el-option>
        </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">确认提交</el-button>
    </el-form-item>
  </el-form>

</el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import * as citys from '@/api/hmmm/citys.js'
import * as directorys from '@/api/hmmm/directorys.js'
import * as subjects from '@/api/hmmm/subjects.js'
import * as tags from '@/api/hmmm/tags.js'
import { direction } from '@/api/hmmm/constants.js'
import * as companys from '@/api/hmmm/companys.js'
import * as questions from '@/api/hmmm/questions.js'
const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKID253qQmv1uZ4LNOFuUwBDxXu40lMkvsfJ',
  SecretKey: 'RenjRu9Azav2uZy84rHUUM4ZGpAJIEzg'
})
export default {
  components: {
    quillEditor
  },
  data () {
    return {

      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote', 'code-block'],
            ['code-block', 'image', 'link']
          ]
        },
        placeholder: ''
      },
      isCheck: [],
      subjectList: [],
      tagList: [],
      directoryList: [],
      userList: [],
      direction: [],
      cityList: [],
      areaList: [],
      companyList: [],
      form: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        difficulty: '1',
        questionType: '1',
        tags: '',
        province: '',
        city: '',
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: 0
          }
        ],
        remarks: '',
        question: '',
        direction: '',
        videoURL: '',
        answer: ''

      },
      imageUrl: '',
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [{ required: true, trigger: 'change' }],
        difficulty: [{ required: this.$route.query, trigger: 'change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.loadSubjectList()
    this.loadCitys()
    this.loadCompanyList()
    if (this.$route.query.id) {
      this.loadQuestionDetail()
    }
    this.direction = direction
  },

  methods: {

    async doEdit () {
      try {
        this.form.id = +this.$route.query.id
        const res = await questions.update(this.form)
        if (res.status === 200) {
          this.$message.success('修改成功')
          this.$router.back()
        }
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },
    async  doAdd () {
      try {
        const res = await questions.add(this.form)
        console.log(res, 'add')
        if (res.status === 200) {
          this.$message.success('添加成功')
          this.$router.back()
        }
      } catch (error) {
        console.log(error)
      }
    },
    onSubmit () {
      this.$refs.questionForm.validate(valid => {
        if (!valid) return
        if (this.form.questionType === '1') {
          const index = this.form.options.findIndex(item => item.code === this.isCheck)
          this.form.options[index].isRight = 1
        } else if (this.form.questionType === '2') {
          this.isCheck.forEach(code => {
            const index = this.form.options.findIndex(item => code === item.code)
            this.form.options[index].isRight = 1
          })
        }
        this.$route.query.id ? this.doEdit() : this.doAdd()
        // this.resetForm()
      })
    },
    async loadQuestionDetail () {
      const res = await questions.detail({ id: this.$route.query.id })
      console.log(res, 'detail')
      this.form = res.data
      if (this.form.questionType === '1') {
        const isRight = this.form.options.find(item => item.isRight)
        this.isCheck = isRight.code
      } else if (this.form.questionType === '2') {
        this.isCheck = this.form.options.filter(item => item.isRight).map(item => item.code)
      }
    },
    resetForm () {
      this.$refs.questionForm.resetFields()
      this.form = {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        difficulty: '1',
        questionType: '1',
        tags: '',
        province: '',
        city: '',
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: 0
          }
        ],
        remarks: '',
        question: '',
        direction: '',
        videoURL: '',
        answer: ''

      }
    },
    removeImg (code) {
      const index = this.form.options.findIndex(item => item.code === code)
      this.$confirm('确认移除改图片?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.options[index].img = ''
        this.$refs.avatarUploader.clearFiles()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    delChoice (code) {
      if (this.form.options.length === 1) {
        return this.$message.error('禁止删除最后一项')
      }
      const index = this.form.options.findIndex(item => item.code === code)
      if (this.form.options[index].img !== '') {
        this.$confirm('确认移除改图片?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.options[index].img = ''
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        this.$confirm('确认删除该选项?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.options.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    addChoice () {
      const mapInfo = { 1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J', 11: 'K', 12: 'L' }
      this.form.options.push({
        code: mapInfo[this.form.options.length + 1],
        title: '',
        img: '',
        isRight: 0
      })
    },
    async loadCompanyList () {
      const res = await companys.list({ page: 1, pagesize: 100 })
      // console.log(res, 'company')
      this.companyList = res.data.items.map(item => ({ company: item.company, id: item.id }))
    },
    async loadSubjectList () {
      try {
        const res = await subjects.list({ page: 1, pagesize: 100 })
        // console.log(res, 'subject')
        if (res.status !== 200) return this.$message.error('获取失败')
        this.subjectList = res.data.items
        console.log(res, 'subject')
      } catch (error) {
        console.log(error)
      }
    },
    loadCitys () {
      this.cityList = citys.provinces()
    },
    async loadSubjectDetail () {
      const tag = await tags.simple({ subjectID: this.form.subjectID })
      console.log(directorys)
      const directory = await directorys.simple({ subjectID: this.form.subjectID })
      console.log(tag, directory)
      console.log(tag.data, 'tag.data')
      this.tagList = tag.data
      this.directoryList = directory.data
    },
    changeCity () {
      this.form.city = ''
      // console.log(citys.citys(this.form.province))
      this.areaList = citys.citys(this.form.province)
    },
    hChange () {
      this.form.catalogID = ''
      this.form.tags = ''
      this.loadSubjectDetail()
    },
    upload (res) {
      console.log(res, 'upload')
      const index = this.form.options.findIndex(item => item.code === res.data.code)
      if (res.file) {
        // 执行上传操作
        cos.putObject({
          Bucket: 'whtop-1314057920', /* 存储桶 */
          Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
          Key: res.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file // 上传文件对象
          // onProgress: (progressData) => {
          //   console.log(JSON.stringify(progressData))

          // }
        }, (err, data) => {
          console.log(err || data)
          // 上传成功之后
          if (data.statusCode === 200) {
            this.imageUrl = `https:${data.Location}`
            console.log(this.imageUrl)
            this.form.options[index].img = `https:${data.Location}`
            // this.$emit('input', `https:${data.Location}`)
          }
          // this.showProgress = false
        })
      }
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }

}
</script>

<style scoped lang='less'>
.add-container{
  .select{
     position: relative;
    padding-bottom: 20px;
    .el-radio{
      margin-right: 5px;
    }
.avatar-uploader{
   text-align: center;
   line-height: 1;
   margin-left: 4px;
   display: inline-block;
   width: 100px ;
   height: 60px ;
  overflow: hidden;
  position: relative;
  top: 25px;
}
 .el-upload {
    border-radius: 6px;
    cursor: pointer;
   .upload-button{
    border: 1px dashed #d9d9d9;
    width: 100px;
    height: 60px;

    &:hover{
       border-color: #409EFF;
       background-color: #fff;
       color: #000;
    }
   }
  }

  .avatar {
     display: inline-block;
    width: 100px;
    height: 58px;
    vertical-align: middle;
text-align: center;

  }
   i{
    width: 18px;
    height: 18px;
    position: absolute;
    z-index: 0;
    top: 18px;
    right: -5px;
    color: #999;
    background: #fff;
    font-size: 18px;
    cursor: pointer;
   }
  }
  padding: 20px;
  .quill-editor {
  ::v-deep .ql-editor {
    height: 200px;
  }

}
}
</style>
